package cn.gxufe.reliable.message.admin.schedule.prodiucer;

import cn.gxufe.reliable.message.admin.domain.RMessage;
import cn.gxufe.reliable.message.admin.mapper.MessageMapper;
import cn.gxufe.reliable.message.admin.schedule.AbstractSchedule;
import cn.gxufe.reliable.message.common.Message;
import cn.gxufe.reliable.message.common.ResultVo;
import com.netflix.hystrix.HystrixCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.Date;
import java.util.List;

/**
 * @author yingjie.rong
 **/
@Component
public class FinishService extends AbstractSchedule {


    private  static final Logger logger = LoggerFactory.getLogger(FinishService.class);

    @Autowired
    private MessageMapper messageMapper;


    @Scheduled(fixedDelay = 1000)
    public synchronized void exec(){
        List<RMessage> messages = messageMapper.selectCanFinish(new Date(System.currentTimeMillis() - (3 * 1000)));
        for (RMessage message: messages ) {
            finish(message);
        }
    }

    public void finish(RMessage message) {
        MultiValueMap<String, Object> requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("messageId", message.getId());
        requestEntity.add("key", message.getKey());
        requestEntity.add("header", message.getHeader());
        requestEntity.add("finishData", message.getFinishData());
        HystrixCommand<ResultVo> hystrixCommand = this.getHystrixCommand(message.getSourceService(), (t) -> {
            String url = "http://" + message.getSourceService() + FINISH_URL;
            ResponseEntity<ResultVo> responseEntity = restTemplate.postForEntity(url, requestEntity, ResultVo.class);
            return responseEntity.getBody();
        });
        ResultVo resultVo = hystrixCommand.execute();
        if(hystrixCommand.isSuccessfulExecution()){
            logger.info("id = {}, key ={} call finish successful !",message.getId(), message.getKey());
            if(Message.RESPONSE_CODE_OK.equals(resultVo.get(ResultVo.CODE))){
                messageMapper.updateFinish( Message.STATUS_FINISH,message.getId(),1,0);
            }else if(Message.RESPONSE_CODE_NOT_FOUNT.equals(resultVo.get(ResultVo.CODE))){
                //todo 数据不一致情况处理
            }else if(Message.RESPONSE_CODE_INCONSISTENT.equals(resultVo.get(ResultVo.CODE))){
                //todo 数据不一致情况处理
            }
        } else {
            logger.info("id = {}, key ={} call finish error !",message.getId(), message.getKey());
            messageMapper.updateFinish(Message.STATUS_FINISH, message.getId(),0,0);
        }
    }
}
